package com.gmail.rborovyk.brightness_widget;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.SeekBar;

public class BrightnessSetupActivity extends Activity {
	static final String PRESET_NAME = "preset.name";
	static final String PRESET_VALUE = "preset.val";
	
	private String mName;
	private int mValue;
	private EditText mNameEditor;
	private SeekBar mSeekBar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.brightness_setup);
		
		Intent intent = getIntent();
		mName = intent.getStringExtra(BrightnessSetupActivity.PRESET_NAME);
		mValue = intent.getIntExtra(BrightnessSetupActivity.PRESET_VALUE, 0);
		
		setupUI();
	}
	
	private void setupUI() {
		mNameEditor = (EditText) findViewById(R.id.brightness_setup_name_edit);
		mNameEditor.setText(mName);
		
		mSeekBar = (SeekBar) findViewById(R.id.brightness_setup_seek_bar);
		mSeekBar.setMax(255);  
		mSeekBar.setKeyProgressIncrement(1); 
		mSeekBar.setProgress(mValue);  
		mSeekBar.setOnSeekBarChangeListener(mSeekListener);
		updateBrightness();
		
		findViewById(R.id.brightness_setup_ok_button).setOnClickListener(mOkListener);
        findViewById(R.id.brightness_setup_cancel_button).setOnClickListener(mCancelListener);
	}
	
	private View.OnClickListener mOkListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int b = mSeekBar.getProgress();
			String name = mNameEditor.getText().toString();
			if(null == name || "".equals(name)){
				name = String.format("%d%%", b*100/255);
			}
			
			Intent data = new Intent();
			data.putExtra(BrightnessSetupActivity.PRESET_NAME, name);
			data.putExtra(BrightnessSetupActivity.PRESET_VALUE, b);
			
			setResult(RESULT_OK, data);
			finish();
		}
	};
    
    private View.OnClickListener mCancelListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			setResult(RESULT_CANCELED);
			finish();
		}
	};
	
	private SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}
		
		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {}
		
		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			mValue = progress;
			updateBrightness();
		}
	};
	
	private void updateBrightness() {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = mValue / (float)255;
		getWindow().setAttributes(lp);
	}
}
